package com.sunzm.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Duration, Durations, StreamingContext}

/**
 *
 * Spark Streaming 单词计数示例程序
 *
 * @author Administrator
 * @version 1.0
 * @date 2021-05-31 18:46
 */
object SparkStreamingWordCountDemo {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf()
      .setAppName(s"${this.getClass.getSimpleName.stripSuffix("$")}")
      .setMaster("local[*]")

    val ssc = new StreamingContext(conf, Durations.seconds(5))

    val lines = ssc.socketTextStream("82.156.210.70", 9999)

    val words: DStream[String] = lines.flatMap(_.split(","))

    val pairs: DStream[(String, Int)] = words.map(word => (word, 1))

    val wordCounts: DStream[(String, Int)] = pairs.reduceByKey(_ + _)

    wordCounts.print()

    ssc.start()             // Start the computation
    ssc.awaitTermination()  // Wait for the computation to terminate
  }
}
